#include "methods.h"

method_t *method_create(char *name, char *description, property_list_t *parameters, void (*callback)(void *, property_list_t *), void *context)
{
    method_t *method = (method_t *)object_new(sizeof(method_t));
    if (!method)
    {
        return NULL;
    }

    method->name = strdup(name);
    method->description = strdup(description);
    method->parameters = parameters;
    method->callback = callback;
    method->context = context;

    return method;
}

method_t *method_list_get(method_list_t *list, char *name)
{
    foreach_in_list(method_t *, method, list)
    {
        if (strcmp(method->name, name) == 0)
        {
            return method;
        }
    }
    return NULL;
}

cJSON *method_list_get_descriptor_json(method_list_t *list)
{
    cJSON *root = cJSON_CreateObject();
    assert(root);

    foreach_in_list(method_t *, method, list)
    {
        cJSON *method_json = cJSON_CreateObject();
        assert(method_json);
        cJSON_AddStringToObject(method_json, "description", method->description);
        cJSON_AddItemToObject(method_json, "parameters", property_list_get_descriptor_json(method->parameters));

        cJSON_AddItemToObject(root, method->name, method_json);
    }
    return root;
}
